#include <cv.h>
#include <highgui.h>

#include <stdio.h>
#include <stdlib.h>
#include<dirent.h>
#include<stdlib.h>

#include "Core.h"
#include "BiCE.h"
#include "ShadowDB.h"

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int fileID;
ShadowDB db;

void extractBiCE(const char* fileName)
{
	IplImage* pImg = NULL; 

	if((pImg = cvLoadImage(fileName,CV_LOAD_IMAGE_GRAYSCALE)) == NULL) {
		printf("Can't load %s\n",fileName);
		exit(1);
	}

	unsigned char *data;
	int height,width;
	height    = pImg->height;
	width     = pImg->width;
	data      = (unsigned char *)pImg->imageData;
	int i,j;
	for(i=0;i<height;i++) for(j=0;j<width;j++) data[i*width+j] /= 255;
	BiCE b(height,width,data);
	//cout << b << endl;
	
	int N = b.postion_sketch_pairs.size();
	for(i=0;i<N;i++) {
		Position p = b.postion_sketch_pairs[i].first;
		Sketch s = b.postion_sketch_pairs[i].second;
		Record r(p,fileID);
		db.add(s,r);
	}
	cvReleaseImage(&pImg);
}

int main( int argc,char* argv[])
{
	if(argc != 3) {
		printf("Usuage: ./exe edge_dir output_db_file\n");
		exit(1);
	}
	
	struct dirent *dptr;
	DIR *dirp;
	
	if((dirp=opendir(argv[1]))==NULL) {
		printf("can't open directory %s\n",argv[1]);
		exit(1);
	}
	
	char buf[1024] = {0};
	while(dptr=readdir(dirp)) {
		if(strstr(dptr->d_name,".jpg") == 0)
			continue;
		sprintf(buf,"%s%s",argv[1],dptr->d_name);
		fileID = atoi(dptr->d_name);
		printf("Extract from %s with file ID %d\n", buf,fileID);
		extractBiCE(buf);
	}

	db.save(argv[2]);
	return 0;
}
